<?php

namespace App\Redis\expired;


use App\Common\Log;
use App\Common\SysContext;
use App\Common\WX\Api\ApiConfig;
use App\Common\WX\Api\OfficialAccount;
use App\Model\t_s_accsuper_config;
use App\Redis\SubscribeEvent;
use App\Redis\SubscribeEventKey;
use App\Traits\TraitConnectDB;
use XWX\Common\H;

/**
 * 定时更新wx access_token
 *
 * Class access_token
 * @package App\Redis\expired
 */
class access_token
{
    use TraitConnectDB;

    function funcHandle($val)
    {
        Log::funcLogDebug(__METHOD__, $val);


        $id = $val;
        $entity_config = t_s_accsuper_config::funcLoad($this->db(), $id);

        $app_config = new ApiConfig();
        $app_config->fill([
            'app_id' => $entity_config->aconfig_app_id,
            'app_secret' => $entity_config->aconfig_app_secret,
        ]);

        //更新access_token
        $app = OfficialAccount::funcIns($app_config);
        //
        $access_token = $app->funcRefreshAccessToken();
        if (H::funcStrHasAnyText($access_token))
        {
            $key = SubscribeEventKey::getKey__access_token($entity_config->aconfig_id);

            //设置1小时过期
            $sub_event = SubscribeEvent::funcIns();
            $sub_event->getRedis()->setEx($key, 60 * 60, $access_token);


            $entity_config->aconfig_access_token = $access_token;
            $entity_config->aconfig_js_ticket = $app->funcGetJsApiTicket($access_token);
            $entity_config->aconfig_js_ticket_wxcard = $app->funcGetJsApiTicket($access_token, 'wx_card');
            $entity_config->aconfig_access_token_date = H::now();
            $entity_config->funcUpdate();

            //更新配置
            SysContext::funcInsStatic()->funcSetX__config($entity_config);
        }

        return $access_token;
    }
}